package concurrent.c_002_Volatile;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * https://www.cnblogs.com/jhxxb/p/10940149.html
 * https://www.cnblogs.com/jhxxb/p/10944691.html
 * volatile，轻量级同步机制，使一个变量在多个线程间可见
 * 保证可见性，禁止指令重拍，不保证原子性
 */
public class T01_HelloVolatile {
    private static int k = 0;
    private static boolean flag = false;

    public static void main(String[] args) throws InterruptedException {
        atomicity();
        visibility();
    }

    // 多运行几次，会出现无法结束的情况
    public static void visibility() throws InterruptedException {
        new Thread(() -> {
            while (true) {
                if (flag) {
                    System.out.println("------------------");
                    break;
                }
            }
        }).start();

        // Thread.sleep(100);

        new Thread(() -> {
            flag = true;
        }).start();
    }

    // 多线程去操作一个共享变量，多运行几次，可以看到不一样的结果
    public static void atomicity() throws InterruptedException {
        ThreadPoolExecutor tpe = new ThreadPoolExecutor(10, 10, 0, TimeUnit.MICROSECONDS, new LinkedBlockingQueue<>(99999));
        for (int i = 0; i < 99999; i++) {
            tpe.execute(() -> {
                k++;
            });
        }
        Thread.sleep(1000);
        System.out.println(k);
        tpe.shutdown();
    }

    public static void orderliness() {

    }
}